package com.scrx.ymg.dao.supermarket;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import com.scrx.ymg.dao.agent.IAgentInfoDao;
import com.scrx.ymg.dao.base.BaseDaoImpl;
import com.scrx.ymg.dao.direct.IDirectDao;
import com.scrx.ymg.dao.seckill.ISeckillDao;
import com.scrx.ymg.dao.user.UserDAOImpl;
import com.scrx.ymg.entity.AgentDrawings;
import com.scrx.ymg.entity.AgentHot;
import com.scrx.ymg.entity.AgentInfo;
import com.scrx.ymg.entity.AgentMoney;
import com.scrx.ymg.entity.AgentSuperMarketSet;
import com.scrx.ymg.entity.BankAccount;
import com.scrx.ymg.entity.DirectInfo;
import com.scrx.ymg.entity.DirectMoney;
import com.scrx.ymg.entity.GoodsType;
import com.scrx.ymg.entity.HeadMoney;
import com.scrx.ymg.entity.OtherInfo;
import com.scrx.ymg.entity.SuperMarketEntrepot;
import com.scrx.ymg.entity.SuperMarketInfo;
import com.scrx.ymg.entity.SupermarketDrawings;
import com.scrx.ymg.entity.SupermarketMoney;
import com.scrx.ymg.entity.SupermarketSet;
import com.scrx.ymg.util.LatLonUtil;

@Repository("superMarketDao")
@Transactional
public class SuperMarketDaoImpl extends BaseDaoImpl implements ISuperMarketDao {
	
	@Autowired
	private IAgentInfoDao agentdao;
    
	
	@Autowired
	private IDirectDao directdao;
	
	@Autowired
	private ISeckillDao seckilldao;
	
	private static final Logger log = LoggerFactory.getLogger(UserDAOImpl.class);

	public List<SuperMarketEntrepot> findAllbyID(String superinfoID) {
		try {
			List<SuperMarketEntrepot> instance;
			Query query = getCurrentSession()
					.createQuery("select se from SuperMarketMapping sm , SuperMarketEntrepot se "
							+ "  where sm.superMarketEntrepot.id=se.id and  sm.superMarketInfo.id=1");
			instance = query.list();
			for (SuperMarketEntrepot superMarketEntrepot : instance) {
				System.out.println(superMarketEntrepot.getProductName());
			}
			return null;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public SuperMarketInfo findone(String username, String password) {
		Query query = getCurrentSession().createQuery("from SuperMarketInfo where account=? and password=? ");
		query.setParameter(0, username);
		query.setParameter(1, password);
		if (query.list().size() > 0) {
			return (SuperMarketInfo) query.list().get(0);
		}
		return null;
	}

	public List<GoodsType> findAll() {
		Query query = getCurrentSession().createQuery("from GoodsType where parentId=0");
		return query.list();
	}

	public List<GoodsType> findOne(String typeID) {
		Query query = getCurrentSession().createQuery("from GoodsType where parentId=?");
		query.setParameter(0, Integer.parseInt(typeID));
		return (List<GoodsType>) query.list();
	}

	@Override
	public List<SuperMarketInfo> findSuperListBylatlon(double maxlon, double maxlat, double minlon, double minlat) {
		Query query = getCurrentSession()
				.createQuery("from SuperMarketInfo where longitude  between ? and ?" + " and latitude between ? and ?");
		query.setParameter(0, minlon);
		query.setParameter(1, maxlon);
		query.setParameter(2, minlat);
		query.setParameter(3, maxlat);
		List<SuperMarketInfo> list = query.list();

		return list;
	}

	@Override
	public SuperMarketInfo findByID(Integer id) {
		log.debug("getting SuperMarketInfo instance with id: " + id);
		Query queryObject = getCurrentSession().createQuery("from SuperMarketInfo where id=?");
		queryObject.setParameter(0, id);
		SuperMarketInfo info = null;
		if (queryObject.list().size() > 0) {
			info = (SuperMarketInfo) queryObject.list().get(0);
		}
		return info;
	}

	public SupermarketMoney findSupermarketMoneyByID(Integer id) {
		log.debug("getting SuperMarketInfo instance with id: " + id);
		Query queryObject = getCurrentSession().createQuery("from SupermarketMoney where superId=:id");
		queryObject.setParameter("id", id);
		SupermarketMoney info = null;
		if (queryObject.list().size() > 0) {
			info = (SupermarketMoney) queryObject.list().get(0);
		}
		return info;
	}

	public String save(SuperMarketInfo superInfo) {
		try {
			int temp = (int) getCurrentSession().save(superInfo);
			if (temp >= 0) {
				return "true";
			}
			return "false";
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public String update(SuperMarketInfo superInfo) {
		try {
			getCurrentSession().update(superInfo);
			return "true";
		} catch (RuntimeException re) {
			return "false";
		}
	}

	public String createSuperMarket(SuperMarketInfo superInfo,SupermarketSet set, MultipartFile liveAction, String liveActionPath,
			MultipartFile license, String licensePath, MultipartFile deliver, String deliverPath, MultipartFile card,
			String cardPath) {
		try {
			getCurrentSession().save(superInfo);
			set.setSupermarketId(superInfo.getId());
			getCurrentSession().save(set);
			liveAction.transferTo(new File(liveActionPath));
//			license.transferTo(new File(licensePath));
//			deliver.transferTo(new File(deliverPath));
//			card.transferTo(new File(cardPath));
			return "true";
		} catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "false";
		}
	}
	public String updateSuperMarket(SuperMarketInfo superInfo,SupermarketSet set,BankAccount  bank, MultipartFile liveAction, String liveActionPath,
			MultipartFile license, String licensePath, MultipartFile deliver, String deliverPath, MultipartFile card,
			String cardPath) {
		try {
			getCurrentSession().update(superInfo);
			//getCurrentSession().update(set);
//			if(bank.getId()==null){
//				getCurrentSession().save(bank);
//			}else{
//				getCurrentSession().update(bank);
//			}
			liveAction.transferTo(new File(liveActionPath));
//			license.transferTo(new File(licensePath));
//			deliver.transferTo(new File(deliverPath));
//			card.transferTo(new File(cardPath));
			return "true";
		} catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "false";
		}
	}

	public Map<Object, Object> getSuperMarketSetinfo(AgentSuperMarketSet set, int pageNum, int pageCount) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			LatLonUtil util = new LatLonUtil();
			StringBuffer hql = new StringBuffer("from AgentSuperMarketSet where status=1 ");
			util.init(set.getSuperName(), "superName", hql);
			util.init(set.getAgentId(), "agentId", hql);
			Query query = getCurrentSession().createQuery(hql.toString());
			query.setMaxResults(pageCount);// 每页多少条
			query.setFirstResult((pageNum - 1) * pageCount);// 第几页
			List<SupermarketSet> setlist = query.list();
			map.put("setlist", setlist);
			map.put("totalpage", (setlist.size() + pageCount - 1) / pageCount);
			return map;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}


	public SupermarketMoney getSupermarketMoneyInfo(int superId) {
		try {
			Query query = getCurrentSession().createQuery("from SupermarketMoney where superId=?");
			query.setParameter(0, superId);
			return (SupermarketMoney)query.uniqueResult();
		} catch (Exception e) {
			return null;
		}
	}


	public String createBankAccountInfo(BankAccount bankAccount) {
            try {
            	this.getCurrentSession().save(bankAccount);
            	return "true";
			} catch (Exception e) {
				return "false";
			}
		
	}


	public BankAccount isNullBankAccountInfo(int superId) {
		try {
			Query query = getCurrentSession().createQuery("from BankAccount where superId=?");
			query.setParameter(0, superId);
			BankAccount bank=(BankAccount)query.uniqueResult();
			return bank;
		} catch (Exception e) {
			return null;
		}
		
	}
	

	public String updateMoneyAndCreateLog(SupermarketMoney money, SupermarketDrawings drawings) {
		
		try {
			getCurrentSession().update(money);
			getCurrentSession().save(drawings);
			return "true";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "false";
		}
		
		
	}

	public Map<Object, Object> getSupermarketDrawings(SupermarketDrawings drawing, int pageNum, int pageCount) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			LatLonUtil util = new LatLonUtil();
			StringBuffer hql =new StringBuffer("from SupermarketDrawings where 1=1 ");
			util.init(drawing.getSuperId(),"superId",hql);
			util.init(drawing.getStatus(),"status",hql);
			hql.append(" order by submitTime");
			Query query=getCurrentSession().createQuery(hql.toString());
			List<SupermarketDrawings> drawings=query.list();
			query.setMaxResults(pageCount);//每页多少条
			query.setFirstResult((pageNum-1)*pageCount);//第几页
			List<SupermarketDrawings> drawingslist=query.list();
			map.put("drawingslist", drawingslist);
			map.put("totalpage", (drawings.size()+pageCount-1)/pageCount);
            return map;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
	}


	public Map<Object, Object> getAllSuperMarketInfo(SuperMarketInfo info, int pageNum, int pageCount) {

		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			LatLonUtil util = new LatLonUtil();
			StringBuffer hql =new StringBuffer("from SuperMarketInfo where 1=1 ");
			util.init(info.getId(),"id",hql);
			util.init(info.getName(),"name",hql);
			util.init(info.getPrincipal(),"principal",hql);
			util.init(info.getIdentityCard(),"identityCard",hql);
			util.init(info.getAccount(),"account",hql);
			util.init(info.getPassword(),"password",hql);
			util.init(info.getAddress(),"address",hql);
			util.init(info.getPhone(),"phone",hql);
			util.init(info.getLongitude(),"longitude",hql);
			util.init(info.getLatitude(),"latitude",hql);
			util.init(info.getPaymentMode(),"paymentMode",hql);
			util.init(info.getAgentId(),"agentId",hql);
			util.init(info.getAgentRegion(),"agentRegion",hql);
			util.initStatus(info.getStatus(),"status",hql);
			Query query=getCurrentSession().createQuery(hql.toString());
			List<SuperMarketInfo> drawings=query.list();
			query.setMaxResults(pageCount);//每页多少条
			query.setFirstResult((pageNum-1)*pageCount);//第几页
			List<SuperMarketInfo> list=query.list();
			AgentInfo ageninfo=null;
//			if(list!=null){
////			for (int i = 0; i < list.size(); i++) {
////				ageninfo=agentdao.getAgentInfoByID(list.get(i).getAgentId());
////				list.get(i).setAgentName(ageninfo.getAgentName());
////			}
//			}
			map.put("list", list);
			map.put("totalpage", (drawings.size()+pageCount-1)/pageCount);
            return map;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
	}


	public BankAccount isNullBankAccountInfoAgent(int agentId) {
		try {
			Query query = getCurrentSession().createQuery("from BankAccount where agentId=?");
			query.setParameter(0, agentId);
			BankAccount bank=(BankAccount)query.uniqueResult();
			return bank;
		} catch (Exception e) {
			return null;
		}
	}

	public BankAccount isNullBankAccountInfoOther(int otherId) {
		try {
			Query query = getCurrentSession().createQuery("from BankAccount where otherId=?");
			query.setParameter(0, otherId);
			BankAccount bank=(BankAccount)query.uniqueResult();
			return bank;
		} catch (Exception e) {
			return null;
		}
	}


	public String updateMoneyAndCreateLog(Object object, AgentDrawings drawings) {
		try {
			getCurrentSession().update(object);
			getCurrentSession().save(drawings);
			return "true";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "false";
		}
	}


	public Map<Object, Object> getAgentDrawings(AgentDrawings drawing, int pageNum, int pageCount) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			LatLonUtil util = new LatLonUtil();
			StringBuffer hql =new StringBuffer("from AgentDrawings where 1=1 ");
			util.init(drawing.getMerchantId(),"merchantId",hql);
			util.init(drawing.getTypeId(), "typeId", hql);
			util.init(drawing.getStatus(),"status",hql);
			hql.append(" order by submitTime desc");
			Query query=getCurrentSession().createQuery(hql.toString());
			List<AgentDrawings> drawings=query.list();
			query.setMaxResults(pageCount);//每页多少条
			query.setFirstResult((pageNum-1)*pageCount);//第几页
			List<AgentDrawings> drawingslist=query.list();
			if(drawingslist!=null&&drawingslist.size()>0){
				for (int i = 0; i < drawingslist.size(); i++) {
					int typeId=drawingslist.get(i).getTypeId();
					int merchantId=drawingslist.get(i).getMerchantId();
					String addId="";
					String userName="";
					String phone="";
					if(typeId==1){//超市
						SuperMarketInfo info =findByID(merchantId);
						addId=info.getIdentityCard();
						userName=info.getPrincipal();
						phone=info.getPhone();
		            }else if(typeId==2){//代理商
		            	AgentInfo info=agentdao.getAgentInfoByID(merchantId);
		            	addId=info.getAddId();
						userName=info.getPrincipal();
						phone=info.getPhone();
		            }else if(typeId==3){//异业
		            	OtherInfo info=seckilldao.getOtherInfoById(merchantId);
		            	addId=info.getOtherCard();
						userName=info.getOtherPrincipal();
						phone=info.getOtherPhone();
		            }else if(typeId==4){//直营
		            	 DirectInfo info=directdao.getDirectInfoById(merchantId);
			            	addId=info.getUserCard();
							userName=info.getUserName();
							phone=info.getPhone();
		            }
					drawingslist.get(i).setAddId(addId);
					drawingslist.get(i).setUserName(userName);
					drawingslist.get(i).setPhone(phone);
				}
			}
			
			map.put("drawingslist", drawingslist);
			map.put("totalpage", (drawings.size()+pageCount-1)/pageCount);
            return map;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
	}


	public String deleteSuperMarketInfo(SuperMarketInfo info) {
          try {
			this.getCurrentSession().delete(info);
			return "true";
		} catch (Exception e) {
			return "false";
		}
	}


	public Map<Object, Object> getSuperMarketInfoByStatus(SuperMarketInfo info, int pageNum, int pageCount) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			LatLonUtil util = new LatLonUtil();
			StringBuffer hql =new StringBuffer("from SuperMarketInfo where 1=1 ");
			util.init(info.getAgentRegion(),"agentRegion",hql);
			util.init(info.getPhone(),"phone",hql);
			util.initStatus(info.getStatus(),"status",hql);
			Query query=getCurrentSession().createQuery(hql.toString());
			List<SuperMarketInfo> drawings=query.list();
			query.setMaxResults(pageCount);//每页多少条
			query.setFirstResult((pageNum-1)*pageCount);//第几页
			List<SuperMarketInfo> list=query.list();
			AgentInfo ageninfo=null;
			if(list!=null){
			for (int i = 0; i < list.size(); i++) {
				ageninfo=agentdao.getAgentInfoByID(list.get(i).getAgentId());
				list.get(i).setAgentName(ageninfo.getAgentName());
			}
			}
			map.put("list", list);
			map.put("totalpage", (drawings.size()+pageCount-1)/pageCount);
            return map;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
	}


	public SuperMarketInfo getsuperMarketInfoBySuperName(String name) {
		try {
			Query query = getCurrentSession().createQuery("from SuperMarketInfo where name=?");
			query.setParameter(0, name);
			return (SuperMarketInfo)query.uniqueResult();
		} catch (Exception e) {
			return null;
		}
	}


	public String updateInfoAndSaveMoney(SuperMarketInfo oldInfo, SupermarketMoney money,List<SuperMarketEntrepot> list) {
        try {
			this.getCurrentSession().update(oldInfo);
			this.getCurrentSession().save(money);
			if(list!=null){
				for (int i = 0; i < list.size(); i++) {
					this.getCurrentSession().save(list.get(i));
				}
			}
			return "true";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "false";
		}
	}


	public BankAccount isNullBankAccountInfoDirect(int directId) {
		try {
			Query query = getCurrentSession().createQuery("from BankAccount where directId=:directId");
			query.setParameter("directId", directId);
			BankAccount bank=(BankAccount)query.uniqueResult();
			return bank;
		} catch (Exception e) {
			return null;
		}
	}


	public String updateMoney(Object object, AgentDrawings drawings, HeadMoney headMoney) {
		try {
			getCurrentSession().update(object);
			getCurrentSession().save(drawings);
			getCurrentSession().update(headMoney);
			return "true";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "false";
		}
	}

	public AgentDrawings getAgentDrawings(int id) {
		try {
			Query query = getCurrentSession().createQuery("from AgentDrawings where id=:id");
			query.setParameter("id", id);
			AgentDrawings bank=(AgentDrawings)query.uniqueResult();
			return bank;
		} catch (Exception e) {
			return null;
		}
	}

	

}
